package com.westcom.vulb.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.westcom.vulb.bean.Session;
import com.westcom.vulb.common.PopMenu;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.logic.share;
import com.westcom.vulb.logic.sheet;
import com.westcom.vulb.protocal.http.Response;




import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ShareMemberActivity extends BasicActivity {
	private listAdapter itemsAdapter;
	private List<userNode> Sheetmemberlist = new ArrayList<userNode>();
	private List<userNode> Showmemberlist = new ArrayList<userNode>();
	private TextView tv_edit_share_member,tv_add_share_member,tv_add_share_member_done;
	private ImageView iv_add_share_member;
	private ListView lv_member = null;
    private Boolean isEditMode = false;
    
    private int mCurrentSheetId;
	private String mCurrentSheetName;
	
	private ProgressDialog mLoadingDialog;
	
	private SessionManager sm;
	private LinearLayout ll_share_member = null;
	private LinearLayout ll_edit_share_member = null;
	

	private OnClickListener l = new OnClickListener()
	{

		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
			switch (v.getId())
			{
				case R.id.tv_edit_sharemember_done:
				case R.id.tv_sharemember_edit:
				{
					isEditMode = !isEditMode;
					if(isEditMode)
					{
						ll_share_member.setVisibility(View.GONE);
						ll_edit_share_member.setVisibility(View.VISIBLE);
					}else
					{
						ll_share_member.setVisibility(View.VISIBLE);
						ll_edit_share_member.setVisibility(View.GONE);
					}
					
					itemsAdapter.notifyDataSetChanged();
				}break;
				case R.id.tv_edit_sharemember_add:
				case R.id.iv_edit_sharemember_add:
				{
					Intent intent = new Intent();
	    	        intent.putExtra("sheetId",mCurrentSheetId);    
	    	        intent.setClass(ShareMemberActivity.this, AddShareMemberActivity.class);
	    	        ShareMemberActivity.this.startActivity(intent);
				}break;
				case R.id.iv_item_sheet_member_del:
				{
					int position = (Integer) v.getTag();
					userNode u = Sheetmemberlist.get(position);		
					showdeleConfrimdialog(u.mName,u.mId);
				}
				default:{}break;
			}
		}};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share_member);
		init();
		
		lv_member=(ListView) findViewById(R.id.lv_member);
		itemsAdapter = new listAdapter(this);
		lv_member.setAdapter(itemsAdapter);
		
		this.tv_edit_share_member = (TextView)findViewById(R.id.tv_sharemember_edit);
		this.tv_add_share_member = (TextView)findViewById(R.id.tv_edit_sharemember_add);
		this.tv_add_share_member_done = (TextView)findViewById(R.id.tv_edit_sharemember_done);
		this.iv_add_share_member = (ImageView)findViewById(R.id.iv_edit_sharemember_add);
		tv_edit_share_member.setOnClickListener(l);
		tv_add_share_member.setOnClickListener(l);
		tv_add_share_member_done.setOnClickListener(l);
		iv_add_share_member.setOnClickListener(l);
		
		mCurrentSheetId =  Integer.parseInt(getIntent().getStringExtra("sheetId"));
        mCurrentSheetName =  getIntent().getStringExtra("sheetName");
        TextView tv_sheet_name = (TextView) findViewById(R.id.tv_sharemember_sheetname);
        tv_sheet_name.setText(mCurrentSheetName);
        
        GetMemeberListTask memberListTask = new GetMemeberListTask();
        mLoadingDialog = ProgressDialog.show(this, this.getResources().getString(R.string.wait),this.getResources().getString(R.string.processing));
        memberListTask.execute("");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		/*getMenuInflater().inflate(R.menu.share_member, menu);*/
		return true;
	}
	private void init()
	{
		ll_share_member = (LinearLayout)findViewById(R.id.ll_sharemember);
		ll_edit_share_member = (LinearLayout)findViewById(R.id.ll_edit_sharemember);
		sm = SessionManager.getInstance();
	}
	public class listAdapter extends BaseAdapter {
		
		private Context context;
		public listAdapter(Context context) 
		{
			this.context = context;
		}
		@Override
		public int getCount() 
		{
			// TODO Auto-generated method stub
			return Showmemberlist == null?0:Showmemberlist.size();
		}

		@Override
		public Object getItem(int arg0) 
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) 
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			// TODO Auto-generated method stub
			View v;				
			if (convertView == null) 
			{
	            v = View.inflate(context, R.layout.item_sheet_member, null);
	        }
			else 
			{
				v = convertView;
			}
			userNode u = Showmemberlist.get(position);
			
			ImageView profile_img = (ImageView) v.findViewById(R.id.iv_item_sheet_member_img);
			if(u.mImg != null)
			{
				profile_img.setImageBitmap(u.mImg);
			}
			
			TextView shareMemberName = (TextView) v.findViewById(R.id.tv_item_sheet_member_name);
			shareMemberName.setText(u.mName);
			
			ImageView del_button =  (ImageView) v.findViewById(R.id.iv_item_sheet_member_del);
			del_button.setOnClickListener(l);
			if(isEditMode == true&&!u.mOwnFlg.equals("1"))
			{	
				del_button.setVisibility(View.VISIBLE);
	        }
	        else
	        {
	        	del_button.setVisibility(View.GONE);
	        }
			del_button.setTag(u.mIndex_in_real_array);
			return v;
		}
	}
	private String getMemberList()
	{
		Response res = null;
    	sheet sh = sheet.getInstanse();
    	res = sh.GetSheetMemberList(sm.getCurrSessionId(),mCurrentSheetId);
    	JSONArray users = (JSONArray)res.data.get("members");
    	Session s = sm.getCurrentSession();
    	userNode u = null;
    	Sheetmemberlist.clear();
    	for(int i = 0;i<users.length();i++)
    	{
    		//"userName":"viking","userId":76
    		try 
    		{
				JSONObject o = (JSONObject) users.get(i);
				u = new userNode(o.getString("userName"),o.getInt("userId"));
				res = s.getProfileImage(true,u.mId);
				String bitmap_str = (String) res.data.get("personImg");
    			u.mImg = account.Base64Str2Bitmap(bitmap_str);
    			u.mStatus = o.getString("memberStatus");
    			u.mOwnFlg = o.getString("ownFlg");
    			Sheetmemberlist.add(u);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	getShowMemberList();
    	if(res.errno == Response.SUCCESS)
    	{
    		return null;
    	}else
    	{
    		return res.errmsg;
    	}
	}
	private void getShowMemberList()
	{
		Showmemberlist.clear();
		userNode u = null;
		for(int i = 0;i<Sheetmemberlist.size();i++)
		{
			u = Sheetmemberlist.get(i);
			u.mIndex_in_real_array = i;
			if(!u.mIsClicked)
			{
				Showmemberlist.add(u);
			}
		}
		return;
	}
	private class GetMemeberListTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) 
        {
        	
            return getMemberList();
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(result != null)
        	{
        		launchToast(result);
        	}
        	itemsAdapter.notifyDataSetChanged();
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}	
        }
	}
	private class DeleteUserTask extends AsyncTask<Integer, Integer, String> {
		int[] IdsTodel = null;
		int mDeleIndex = -1;
        @Override
        protected String doInBackground(Integer... params) 
        {
        	Response res = null;
        	sheet sh = sheet.getInstanse();
        	IdsTodel = new int[params.length];
        	for(int i = 0;i<params.length;i++)
        	{
        		IdsTodel[i] = params[i];
        	}
        	res = sh.GroupForceRetire(sm.getCurrSessionId(),mCurrentSheetId,IdsTodel);
        	if(res.errno == Response.SUCCESS)
        	{
        		return null;
        	}
            return res.errmsg;
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(result == null)
        	{
        		deleUserFromArray(IdsTodel);
        	}else
        	{
        		launchToast(result);
        	}
        	resetSheetmemberlist();
        	itemsAdapter.notifyDataSetChanged();
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
    }
	
	protected void showdeleConfrimdialog(String title,final int userId) 
	{
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(title);
		builder.setMessage(R.string.del_confirm);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				DeleteUserTask deletask = new DeleteUserTask();
				Integer [] d_t = new Integer [1];
				d_t[0] = Integer.valueOf(userId);
				deletask.execute(d_t);
				dialog.dismiss();
				mLoadingDialog = ProgressDialog.show(ShareMemberActivity.this,getResources().getString(R.string.wait),getResources().getString(R.string.processing));
			}});
		
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}});
		builder.create().show();
	}
	private void resetSheetmemberlist()
	{
		userNode u = null;
		for(int i = 0;i<Sheetmemberlist.size();i++)
		{
			u = Sheetmemberlist.get(i);
			u.mIndex_in_real_array = i;
			u.mIsClicked = false;
		}
		this.getShowMemberList();
	}
	private void deleUserFromArray(int[] IdsToDel)
	{
		userNode u = null;
		for(int i = 0;i<Sheetmemberlist.size();i++)
		{
			u = Sheetmemberlist.get(i);
			for(int j = 0;j<IdsToDel.length;j++)
			{
				if(u.mId == IdsToDel[j])
				{
					
					Sheetmemberlist.remove(i);
				}
			}
			
		}
		this.getShowMemberList();
	}
}
